import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { RootState } from '../store';
import { IOrderSelectionInfo, getOrderSelectList } from 'api/order';

const namespace = 'order/list';

interface IInitialState {
  loading: boolean;
  current?: number;
  size?: number;
  total: number;
  contractList: IOrderSelectionInfo[];
}

const initialState: IInitialState = {
  loading: true,
  current: 1,
  size: 10,
  total: 0,
  contractList: [],
};

export const getList = createAsyncThunk(`${namespace}/getSelectList`, async (params: any) => {
  const result = await getOrderSelectList(params);
  return {
    list: result.data.records,
    total: result.data.total,
    size: params.size,
    current: params.current,
  };
});

const orderListSelectSlice = createSlice({
  name: namespace,
  initialState,
  reducers: {
    clearPageState: () => initialState,
  },
  extraReducers: (builder) => {
    builder
      .addCase(getList.pending, (state) => {
        state.loading = true;
      })
      .addCase(getList.fulfilled, (state, action) => {
        state.loading = false;
        state.contractList = action.payload?.list;
        state.total = action.payload?.total;
        state.size = action.payload?.size;
        state.current = action.payload?.current;
      })
      .addCase(getList.rejected, (state) => {
        state.loading = false;
      });
  },
});

export const { clearPageState } = orderListSelectSlice.actions;

export const selectOrderListSelect = (state: RootState) => state.order;

export default orderListSelectSlice.reducer;
